package com.fire.market.order.tcc.impl;

import com.fire.market.order.api.request.OrderCreateParam;
import com.fire.market.order.manager.OrderManager;
import com.fire.market.order.tcc.StockDecreaseTcc;
import io.seata.core.context.RootContext;
import io.seata.rm.tcc.TwoPhaseResult;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * OrderCreateTccImpl
 *
 * @author zwd
 * @date 2021/7/24
 * @desc
 */
@Service
public class StockDecreaseTccImpl implements StockDecreaseTcc {
    private static final Logger LOGGER = LoggerFactory.getLogger("ApplicationRequestFilter");

    @Resource
    private OrderManager orderManager;

    @Override
    public TwoPhaseResult prepare(OrderCreateParam param) {
        String xid = RootContext.getXID();
        String tccInfo = ":::: TccActionOne prepare, xid:" + xid + ", param:" + param;
        LOGGER.info(tccInfo);
        orderManager.decreaseStock(param.getItemId(), param.getAmount());
        return new TwoPhaseResult(true, tccInfo);
    }

    @Override
    public TwoPhaseResult commit(BusinessActionContext actionContext) {
        String xid = RootContext.getXID();
        OrderCreateParam param = (OrderCreateParam)actionContext.getActionContext("OrderCreateParam");
        String tccInfo = ":::: TccActionOne rollback, xid:" + xid + ", param:" + param.toString();
        return new TwoPhaseResult(true, tccInfo);
    }

    @Override
    public TwoPhaseResult rollback(BusinessActionContext actionContext) {
        String xid = RootContext.getXID();
        OrderCreateParam param = (OrderCreateParam)actionContext.getActionContext("OrderCreateParam");
        String tccInfo = ":::: TccActionOne rollback, xid:" + xid + ", param:" + param.toString();
        LOGGER.info(tccInfo);
        orderManager.increaseStock(param.getItemId(), param.getAmount());
        return new TwoPhaseResult(true, tccInfo);
    }
}
